import jwt from 'jsonwebtoken'
import pool from '../db'
import { getCookie, createError, defineEventHandler } from 'h3'
import type { ApiResponse, UserInfo, DecodedToken } from '~/types/common'

export default defineEventHandler(async (event) => {
  try {
    // 从cookie中获取token
    const refreshToken = getCookie(event, 'refreshToken')

    if (!refreshToken) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌不存在',
        message: '刷新令牌不存在，请重新登录'
      })
    }

    // 验证刷新token
    let decoded: any
    try {
      decoded = jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN_SECRET || 'your-refresh-secret-key'
      )
    } catch (error) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Invalid refresh token',
        message: '刷新令牌无效，请重新登录'
      })
    }

    // 检查token类型
    if (decoded.type !== 'refresh') {
      throw createError({
        statusCode: 401,
        statusMessage: 'Invalid token type',
        message: '无效的令牌类型'
      })
    }
    // 获取数据库连接
    const connection = await pool.getConnection()

    // 查询用户信息（不包含密码和salt等敏感信息）
    const [data]: any[][] = await connection.execute(
      'SELECT id, nickname, avatar FROM users WHERE id = ?',
      [decoded.userId]
    )

    // 释放连接
    connection.release()

    if (Array.isArray(data) && data.length === 0) {
      throw createError({
        statusCode: 404,
        statusMessage: '用户不存在',
        message: '未找到对应ID的用户信息'
      })
    }
    // 返回用户信息
    const userInfo: UserInfo = {
      id: data[0].id,
      nickname: data[0].nickname,
      avatar: data[0].avatar
    }
    return {
      code: 200,
      statusMessage: '成功',
      message: '获取个人信息成功',
      data: userInfo
    } as ApiResponse<UserInfo>
  } catch (error: any) {
    // 所有错误已经在前面的特定处理中被捕获
    // 这里只处理未预期的错误
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
      message: '获取个人信息时发生错误'
    })
  }
})
